<template>
    <div class="sdy-goods-list">
        <Teleport to=".hearder-show">
            <div class="header">
                <div class="back" >
                    <svg class="icon" aria-hidden="true" @click="$router.go(-1)">
                        <use xlink:href="#icon-back"></use>
                     </svg>
                </div>
                
              
            </div>
            </Teleport>
        <van-card v-for="item in goodsList" num="10" :price="item.originprice" :desc="item.desc" :title="item.proname"
            :thumb="item.img1">
            <template #footer>
                <van-button size="mini" type="warning" @click="goToDetail(item.proid)">查看详情</van-button>
                <van-button size="mini" type="danger" @click="addCart(item.proid)">加入购物车</van-button>
            </template>
        </van-card>
    </div>
</template>
  
<script setup lang="ts">
import {Teleport}from 'vue'
import { useRoute, useRouter, type RouteLocationNormalizedLoaded, type Router } from 'vue-router'
import { onMounted, ref } from 'vue'
import { searchListApi } from '@/api/goods'
import type { MyHotItem } from '@/config/interface'
import { addCartApi } from '@/api/cart'
import { Toast } from 'vant'

const $route: RouteLocationNormalizedLoaded = useRoute()
const $router: Router = useRouter()
const setLocalStorage = (text: string): void => {
    const historyList: string[] = JSON.parse(window.localStorage.getItem('history') as string) || []

    const res: boolean = historyList.indexOf(text) !== -1

    if (res) return
    historyList.push(text)
    window.localStorage.setItem('history', JSON.stringify(historyList))}

const count = ref<number>(1)

const goodsList = ref<MyHotItem[]>([])
const getGoodsList = async (text: string) => {

    const res = await searchListApi(text, count.value)
    goodsList.value = res.data
    console.log(res.data)
}


const goToDetail = (id: string) => {

    $router.push({ path: '/detail', query: { proid: id } })
}


const addCart = async (id: string) => {
    console.log(`将 id 为 ${id} 的商品加入购物车`)

    const user_id = window.localStorage.getItem('user_id')
    const token = window.localStorage.getItem('token')


    if (!user_id || !token) {

        Toast({
            message: '您还没有登录'
        })
        return
    }


    const res = await addCartApi(user_id, id)
    console.log(res)

    // 判断
    if (((res as unknown) as { code: string }).code=== '200') Toast({ message: '加入购物车成功' })
}

onMounted(() => {
    const searchText = $route.query.search
    searchText && setLocalStorage(searchText as string)
    searchText && getGoodsList(searchText as string)
})

</script>
  
<style scoped lang="scss">
.sdy-goods-list {
    height: 100%;
    overflow-y: auto;
}
</style>
  